package lmusica;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import java.sql.*;


public class cdatos extends javax.swing.JFrame {

    Vector vmusica = new Vector(4, 4);
    String cancion, Art, Album, Genero;
    private Connection conn = null;
    ListIterator itr = vmusica.listIterator();
    Ncancion element = new Ncancion();
    ListIterator itr2 = vmusica.listIterator();
    DefaultTableModel modelo = new DefaultTableModel();
    int columna = 1;
    int conta =0;
    public cdatos() {

        initComponents();


    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFrame1 = new javax.swing.JFrame();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        jRadioButton3 = new javax.swing.JRadioButton();
        jRadioButton4 = new javax.swing.JRadioButton();
        jLabel5 = new javax.swing.JLabel();
        jMenuBar2 = new javax.swing.JMenuBar();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem8 = new javax.swing.JMenuItem();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenuItem5 = new javax.swing.JMenuItem();
        jMenuItem6 = new javax.swing.JMenuItem();
        buttonGroup1 = new javax.swing.ButtonGroup();
        jButton1 = new javax.swing.JButton();
        ncancion = new javax.swing.JTextField();
        art = new javax.swing.JTextField();
        album = new javax.swing.JTextField();
        genero = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        Basedatos = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();

        jFrame1.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        jFrame1.setTitle("Tabla");
        jFrame1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jFrame1.setMinimumSize(new java.awt.Dimension(600, 300));
        jFrame1.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                llena_jframe(evt);
            }
        });

        jTable1.setModel(modelo);
        jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
        jScrollPane1.setViewportView(jTable1);

        jRadioButton1.setSelected(true);
        jRadioButton1.setText("Columna 1");
        jRadioButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                columna1(evt);
            }
        });

        jRadioButton2.setText("Columna 2");
        jRadioButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                columna2(evt);
            }
        });

        jRadioButton3.setText("Columna 3");
        jRadioButton3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                columna3(evt);
            }
        });

        jRadioButton4.setText("Columna 4");
        jRadioButton4.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                columna4(evt);
            }
        });

        jLabel5.setText("Columna a ordenar");

        jMenu2.setText("Ordenar");

        jMenuItem8.setText("Burbuja");
        jMenuItem8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                burbuja(evt);
            }
        });
        jMenu2.add(jMenuItem8);

        jMenuItem4.setText("Selection Sort ");
        jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectionsort(evt);
            }
        });
        jMenu2.add(jMenuItem4);

        jMenuItem5.setText("Insertion Sort");
        jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Inserccion(evt);
            }
        });
        jMenu2.add(jMenuItem5);

        jMenuItem6.setText("Quick Sort");
        jMenuItem6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                llamaquicksort(evt);
            }
        });
        jMenu2.add(jMenuItem6);

        jMenuBar2.add(jMenu2);

        jFrame1.setJMenuBar(jMenuBar2);

        javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
        jFrame1.getContentPane().setLayout(jFrame1Layout);
        jFrame1Layout.setHorizontalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jFrame1Layout.createSequentialGroup()
                .addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jFrame1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 552, Short.MAX_VALUE))
                    .addGroup(jFrame1Layout.createSequentialGroup()
                        .addGap(240, 240, 240)
                        .addComponent(jLabel5)))
                .addContainerGap())
            .addGroup(jFrame1Layout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addComponent(jRadioButton1)
                .addGap(44, 44, 44)
                .addComponent(jRadioButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 88, Short.MAX_VALUE)
                .addComponent(jRadioButton3)
                .addGap(70, 70, 70)
                .addComponent(jRadioButton4)
                .addGap(40, 40, 40))
        );
        jFrame1Layout.setVerticalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jFrame1Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5)
                .addGap(18, 18, 18)
                .addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jRadioButton4)
                    .addComponent(jRadioButton1)
                    .addComponent(jRadioButton2)
                    .addComponent(jRadioButton3))
                .addGap(31, 31, 31))
        );

        buttonGroup1.add(jRadioButton1);
        buttonGroup1.add(jRadioButton2);
        buttonGroup1.add(jRadioButton3);
        buttonGroup1.add(jRadioButton4);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Lista de Canciones");

        jButton1.setText("Insertar");
        jButton1.setEnabled(false);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                insertar(evt);
            }
        });

        ncancion.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));

        jLabel1.setText("Nombre cancion");

        jLabel2.setText("Artista");

        jLabel3.setText("Album");

        jLabel4.setText("Genero");

        jButton2.setText("<<");
        jButton2.setEnabled(false);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                anterior(evt);
            }
        });

        jButton3.setText(">>");
        jButton3.setEnabled(false);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                siguiente(evt);
            }
        });

        jButton4.setText("Consultar");
        jButton4.setEnabled(false);
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mostrar_jtable(evt);
            }
        });

        jButton5.setText("Modificar");
        jButton5.setEnabled(false);
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                modificar(evt);
            }
        });

        jButton6.setText("Borrar");
        jButton6.setEnabled(false);
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                borrar(evt);
            }
        });

        jMenu1.setText("Archivo");
        jMenu1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cargarBD(evt);
            }
        });

        jMenuItem2.setText("Cargar");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cargarcsv(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuItem1.setText("Guardar a .csv");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                guardaracsv(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        Basedatos.setText("cargar base de datos");
        Basedatos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cargaraBD(evt);
            }
        });
        jMenu1.add(Basedatos);

        jMenuItem3.setText("Salir");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                salir(evt);
            }
        });
        jMenu1.add(jMenuItem3);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(14, 14, 14)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel2))
                                .addGap(16, 16, 16))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(genero)
                            .addComponent(album)
                            .addComponent(art)
                            .addComponent(ncancion, javax.swing.GroupLayout.PREFERRED_SIZE, 312, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ncancion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(art, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(album, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(genero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton5)
                    .addComponent(jButton6)
                    .addComponent(jButton4)
                    .addComponent(jButton3))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void anterior(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_anterior

        try {
            element = (Ncancion) itr.previous();
            cancion = element.getNcancion();
            ncancion.setText(cancion);
            Art = element.getArtist();
            art.setText(Art);
            Album = element.getAlbu();
            album.setText(Album);
            Genero = element.getGener();
            genero.setText(Genero);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "No existe elemento anterior","Error",JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_anterior

    private void mostrar_jtable(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mostrar_jtable
jFrame1.setVisible(true);
    }//GEN-LAST:event_mostrar_jtable

    private void insertar(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_insertar
        if (ncancion.getText().equals("") || art.getText().equals("") || album.getText().equals("") || genero.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Todos los campos son obligatorios","Error",JOptionPane.ERROR_MESSAGE);
        } else {           
           jButton2.setEnabled(true);
           jButton3.setEnabled(true);
           jButton4.setEnabled(true);///visibilidad de los botones 
           jButton5.setEnabled(true);
           jButton6.setEnabled(true);

            Ncancion Objeto = new Ncancion();
            cancion = ncancion.getText();
            Art = art.getText();
            Album = album.getText();
            Genero = genero.getText();

            Objeto.setNcancion(cancion);   //enviar el objeto  
            Objeto.setArtist(Art);
            Objeto.setAlbu(Album);
            Objeto.setGener(Genero);

            vmusica.addElement(Objeto);//v musica vector 

            System.out.println("nº de elementos " + vmusica.size());

            itr = vmusica.listIterator();
            ncancion.setText("");
            art.setText("");
            album.setText("");//limpiar el campo de texto
            genero.setText("");
        }
    }//GEN-LAST:event_insertar

    private void siguiente(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_siguiente

        try {
            element = (Ncancion) itr.next();
            cancion = element.getNcancion();
            ncancion.setText(cancion);
            Art = element.getArtist();
            art.setText(Art);
            Album = element.getAlbu();
            album.setText(Album);
            Genero = element.getGener();
            genero.setText(Genero);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "No existe elemento siguiente","Error",JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_siguiente

    private void modificar(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_modificar
        
            if (ncancion.getText().equals("") || art.getText().equals("") || album.getText().equals("") || genero.getText().equals(""))
               {
            JOptionPane.showMessageDialog(null, "Todos los campos son obligatorios","Error",JOptionPane.ERROR_MESSAGE);
                }
            else{
            Ncancion Objeto = new Ncancion();//instanciar objeto
            cancion = ncancion.getText();
            Art = art.getText();//string 
            Album = album.getText();
            Genero = genero.getText();
            Objeto.setNcancion(cancion);
            Objeto.setArtist(Art);
            Objeto.setAlbu(Album);//objeto
            Objeto.setGener(Genero);
            if (itr.previousIndex() != -1) {
                vmusica.setElementAt(Objeto, itr.nextIndex() - 1);//elemento y pocision donde vamios a meter
            } else {
                vmusica.setElementAt(Objeto, itr.nextIndex());
            }
            ncancion.setText("");
            art.setText("");//vacia los campos de texto
            album.setText("");
            genero.setText("");
            itr = vmusica.listIterator();
            }       
    }//GEN-LAST:event_modificar

    private void borrar(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_borrar
        
            if (itr.previousIndex() != -1) {
                vmusica.remove(itr.nextIndex() - 1);
            } else {
                vmusica.remove(itr.nextIndex());
            }
            ncancion.setText("");
            art.setText("");
            album.setText("");
            genero.setText("");           
            itr = vmusica.listIterator();
            if(vmusica.isEmpty()==true){
               jButton2.setEnabled(false);
               jButton3.setEnabled(false);
               jButton4.setEnabled(false);
               jButton5.setEnabled(false);
               jButton6.setEnabled(false);                         
            }           
    }//GEN-LAST:event_borrar

    private void llena_jframe(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_llena_jframe
     modelo = new DefaultTableModel(){
     @Override
   public boolean isCellEditable(int rowIndex, int vColIndex) {
   return false;
                                                              }
                                    };
     jTable1.setModel(modelo);

     modelo.addColumn("Cancion");
     modelo.addColumn("Artista");
     modelo.addColumn("Album");
     modelo.addColumn("Genero");

for(int i=0;i<vmusica.size();i++){
    Ncancion objeto= new Ncancion();
    objeto=(Ncancion)vmusica.elementAt(i);
    String[] fila = {objeto.getNcancion(), objeto.getArtist(),objeto.getAlbu(), objeto.getGener() };
    modelo.addRow(fila);
                             }
     ncancion.setText("");
     art.setText("");
     album.setText("");
     genero.setText("");           
     itr = vmusica.listIterator();
     
    }//GEN-LAST:event_llena_jframe

    private void burbuja(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_burbuja
     conta =0;
     String t = null;
     String c = null;
      for(int i=0;i<vmusica.size()-1;i++){
       for (int j=0;j<vmusica.size()-1;j++){
        Ncancion objeto= new Ncancion();
        objeto=(Ncancion)vmusica.elementAt(j);
        Ncancion objeto2= new Ncancion();
        objeto2=(Ncancion)vmusica.elementAt(j+1);
        
        switch(columna){
            case 1:
        t= objeto.getNcancion();
        c= objeto2.getNcancion();
        break;
            case 2:
        t= objeto.getArtist();
        c= objeto2.getArtist();
        break;
            case 3:
        t= objeto.getAlbu();
        c= objeto2.getAlbu();
        break;
            case 4:
        t= objeto.getGener();
        c= objeto2.getGener();
        break;
                     }


            if (t.compareTo(c) > 0){
             Ncancion temp =new Ncancion();
             temp=objeto;
             vmusica.setElementAt(objeto2,j);
             vmusica.setElementAt(temp,j+1);
             conta++;
                                   }

                                            }
                                       }
     jFrame1.dispose();
     jFrame1.setVisible(true);
     if (conta>0)
     JOptionPane.showMessageDialog(null, "Se hicieron "+ conta + " iteraciones","Mensaje",JOptionPane.INFORMATION_MESSAGE);
     else
     JOptionPane.showMessageDialog(null, "Sin iteraciones, la columna ya se encuentra en orden","Mensaje",JOptionPane.INFORMATION_MESSAGE);
    }//GEN-LAST:event_burbuja

    private void selectionsort(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectionsort

     int minindex;
     conta=0;
        String argumento= null;
        String elemento= null;

     for(int i=0;i<vmusica.size()-1;i++){
         minindex=i;
       for (int j=i+1;j<vmusica.size();j++){
        Ncancion objeto= new Ncancion();
        objeto=(Ncancion)vmusica.elementAt(j);       
        Ncancion objetomenor= new Ncancion();
        objetomenor=(Ncancion)vmusica.elementAt(minindex);

        switch(columna){
            case 1:
        argumento= objetomenor.getNcancion();
        elemento= objeto.getNcancion();
        break;
            case 2:
        argumento= objetomenor.getArtist();
        elemento= objeto.getArtist();
        break;
            case 3:
        argumento= objetomenor.getAlbu();
        elemento= objeto.getAlbu();
        break;
            case 4:
        argumento= objetomenor.getGener();
        elemento= objeto.getGener();
        break;
                     }

            if (elemento.compareTo(argumento) < 0){
             minindex=j;
                                                  }

                                            }
             if (minindex!=i){
             Ncancion index = new Ncancion();
             index=(Ncancion)vmusica.elementAt(minindex);

             Ncancion temp =new Ncancion();
             temp=(Ncancion)vmusica.elementAt(i);


             vmusica.setElementAt(index,i);
             vmusica.setElementAt(temp,minindex);
             conta++;
             }
                                       }
     jFrame1.dispose();
     jFrame1.setVisible(true);
     if (conta>0)
     JOptionPane.showMessageDialog(null, "Se hicieron "+ conta + " iteraciones","Mensaje",JOptionPane.INFORMATION_MESSAGE);
     else
     JOptionPane.showMessageDialog(null, "Sin iteraciones, la columna ya se encuentra en orden","Mensaje",JOptionPane.INFORMATION_MESSAGE);
    }//GEN-LAST:event_selectionsort

    private void columna1(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_columna1
columna = 1;        // TODO add your handling code here:
    }//GEN-LAST:event_columna1

    private void columna2(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_columna2
columna = 2;        // TODO add your handling code here:
    }//GEN-LAST:event_columna2

    private void columna3(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_columna3
columna = 3;        // TODO add your handling code here:
    }//GEN-LAST:event_columna3

    private void columna4(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_columna4
columna = 4;        // TODO add your handling code here:
    }//GEN-LAST:event_columna4

    private void Inserccion(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Inserccion
      conta=0;
      String auxx=null;
      String d=null;

 for (int i=1; i<vmusica.size(); i++) {
      
            Ncancion aux= new Ncancion();
            aux =(Ncancion)vmusica.elementAt(i);
            
            int j = i-1;
            Ncancion objeto= new Ncancion();
            objeto =(Ncancion)vmusica.elementAt(j);

              switch(columna){
            case 1:
            auxx= aux.getNcancion();
            d= objeto.getNcancion();
               break;
            case 2:
            auxx= aux.getArtist();
            d= objeto.getArtist();
              break;
            case 3:
            auxx= aux.getAlbu();
            d= objeto.getAlbu();
              break;
            case 4:
            auxx= aux.getGener();
            d= objeto.getGener();
             break;
                     }


      while(j>=0 && auxx.compareTo(d)<0){
          
         objeto= new Ncancion();
         objeto =(Ncancion)vmusica.elementAt(j);
         vmusica.setElementAt(objeto,j+1);
         conta++;
         
         j--;
           if(j>=0){
             objeto= new Ncancion();
             objeto =(Ncancion)vmusica.elementAt(j);
              
                switch(columna){
            case 1:           
            d= objeto.getNcancion();
               break;
            case 2:
            d= objeto.getArtist();
              break;
            case 3:
            d= objeto.getAlbu();
              break;
            case 4:
            d= objeto.getGener();
             break;
                              }
                   }
                                       }
             
               vmusica.setElementAt(aux,j+1);
               
                                    }

     jFrame1.dispose();
     jFrame1.setVisible(true);
     if (conta>0)
     JOptionPane.showMessageDialog(null, "Se hicieron "+ conta + " iteraciones","Mensaje",JOptionPane.INFORMATION_MESSAGE);
     else
     JOptionPane.showMessageDialog(null, "Sin iteraciones, la columna ya se encuentra en orden","Mensaje",JOptionPane.INFORMATION_MESSAGE);
    }//GEN-LAST:event_Inserccion

    private void llamaquicksort(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_llamaquicksort
        conta=0;
     quicksort(0,vmusica.size()-1);
     jFrame1.dispose();
     jFrame1.setVisible(true);
     if (conta>0)
     JOptionPane.showMessageDialog(null, "Se hicieron "+ conta + " iteraciones","Mensaje",JOptionPane.INFORMATION_MESSAGE);
     else
     JOptionPane.showMessageDialog(null, "Sin iteraciones, la columna ya se encuentra en orden","Mensaje",JOptionPane.INFORMATION_MESSAGE);
    }//GEN-LAST:event_llamaquicksort

private void salir(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salir
System.exit(0);        // TODO add your handling code here:
}//GEN-LAST:event_salir

private void guardaracsv(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardaracsv

    int verifica=0;
    JFileChooser fc=new JFileChooser(System.getProperty("user.dir"));
     FileNameExtensionFilter filtro = new FileNameExtensionFilter("Tabla excel CSV", "csv");
     fc.setAcceptAllFileFilterUsed(false);
     fc.addChoosableFileFilter(filtro);
     
     fc.showSaveDialog(this); //Muestra el diálogo
     File f = fc.getSelectedFile();
   //  if (f.exists()==true){
   //  f.delete();
    //                      }//cuadro de texto de guardar
      try{      
         jButton1.setEnabled(true);
         Exel o = new Exel();//intanciamos clase exel
         itr2 = vmusica.listIterator();//para recorrer el vector
         while(itr2.hasNext()==true)//si itr2 tiene un siguiente element
        {
            try {
                element = (Ncancion) itr2.next();
                o.escribiracsv(f.getAbsolutePath(), element.getNcancion(), element.getArtist(), element.getAlbu(), element.getGener(),verifica);
                verifica=1;               //ruta directorio   //string de cada elemento
               }catch (IOException ex) {
                Logger.getLogger(cdatos.class.getName()).log(Level.SEVERE, null, ex);
                break;
                                       }
                                    }

     }
catch(Exception e){}
}//GEN-LAST:event_guardaracsv

private void cargarcsv(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cargarcsv
        try{
           try {
            jFrame1.dispose();
            JFileChooser fc = new JFileChooser(System.getProperty("user.dir"));
            FileNameExtensionFilter filtro = new FileNameExtensionFilter("Tabla excel CSV", "csv");
            fc.setAcceptAllFileFilterUsed(false);
            fc.addChoosableFileFilter(filtro);

            fc.showOpenDialog(fc);
            File f = fc.getSelectedFile();
           
            vmusica = new Vector(4, 4);
            
            CsvReader reader = null;
            reader = new CsvReader(f.getAbsolutePath());
            reader.setDelimiter(';');
            jButton1.setEnabled(true);
            
            try {
                //metodo de leer archivo
                while (reader.readRecord()) {
                    Ncancion Objeto = new Ncancion();
                    Objeto.setNcancion(reader.get(0));   //enviar el objeto
                    Objeto.setArtist(reader.get(1));
                    Objeto.setAlbu(reader.get(2));
                    Objeto.setGener(reader.get(3));
                    vmusica.addElement(Objeto);
                    //v musica vector
                                            }
                if(vmusica.isEmpty()==false){                
                jButton4.setEnabled(true);
                jButton2.setEnabled(true);
                jButton3.setEnabled(true);
                jButton5.setEnabled(true);
                jButton6.setEnabled(true);
                Ncancion inicio = new Ncancion();
                inicio=(Ncancion)vmusica.elementAt(0);
                ncancion.setText(inicio.getNcancion());
                art.setText(inicio.getArtist());
                album.setText(inicio.getAlbu());
                genero.setText(inicio.getGener());
                                            }
                else{
                jButton4.setEnabled(false);
                jButton2.setEnabled(false);
                jButton3.setEnabled(false);
                jButton5.setEnabled(false);
                jButton6.setEnabled(false);
                ncancion.setText("");
                art.setText("");
                album.setText("");
                genero.setText("");
                }
                itr = vmusica.listIterator();


                
                } catch (IOException ex) {
                Logger.getLogger(cdatos.class.getName()).log(Level.SEVERE, null, ex);
                }

        } catch (FileNotFoundException ex) {
            Logger.getLogger(cdatos.class.getName()).log(Level.SEVERE, null, ex);
        }
        }
        catch(Exception e){}
}//GEN-LAST:event_cargarcsv

private void cargarBD(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cargarBD
        try
        {
            vmusica = new Vector(4, 4);    
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            conn = DriverManager.getConnection("jdbc:odbc:CristianMySQLServer");
            Statement st=conn.createStatement();
            ResultSet rs=st.executeQuery("SELECT nombreCancion , artista , genero , album FROM tabla1");
            while(rs.next()){
                Ncancion Objeto = new Ncancion();
                Objeto.setNcancion(rs.getString(1));   //enviar el objeto
                    Objeto.setArtist(rs.getString(2));
                    Objeto.setAlbu(rs.getString(3));
                    Objeto.setGener(rs.getString(4));
                    vmusica.addElement(Objeto);
            System.out.println(rs.getString(1)+"   "+rs.getString(2)+"   "+rs.getString(3)+"   "+rs.getString(4));
            }
 
            if(conn!=null)
            {
                DatabaseMetaData dbmd = conn.getMetaData(); //get MetaData to confirm connection
                System.out.println("Connection to "+dbmd.getDatabaseProductName()+" "+
	        dbmd.getDatabaseProductVersion()+" successful.\n");
                //System.out.println(conn.getClientInfo("localhost"));
                conn.close();
            }
            
              

        }catch(Exception ex)
        {
            ex.printStackTrace();
        }    
}//GEN-LAST:event_cargarBD

private void cargaraBD(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cargaraBD
        try
        {
            vmusica = new Vector(4, 4);    
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            conn = DriverManager.getConnection("jdbc:odbc:CristianMySQLServer");
            Statement st=conn.createStatement();
            ResultSet rs=st.executeQuery("SELECT nombreCancion , artista , genero , album FROM tabla1");
            while(rs.next()){
                Ncancion Objeto = new Ncancion();
                    Objeto.setNcancion(rs.getString(1));   //enviar el objeto
                    Objeto.setArtist(rs.getString(2));
                    Objeto.setAlbu(rs.getString(3));
                    Objeto.setGener(rs.getString(4));
                    vmusica.addElement(Objeto);
            System.out.println(rs.getString(1)+"   "+rs.getString(2)+"   "+rs.getString(3)+"   "+rs.getString(4));
            }
 
            if(conn!=null)
            {
                DatabaseMetaData dbmd = conn.getMetaData(); //get MetaData to confirm connection
                System.out.println("Connection to "+dbmd.getDatabaseProductName()+" "+
	        dbmd.getDatabaseProductVersion()+" successful.\n");
                //System.out.println(conn.getClientInfo("localhost"));
                conn.close();
            }
                if(vmusica.isEmpty()==false){                
                jButton4.setEnabled(true);
                jButton2.setEnabled(true);
                jButton3.setEnabled(true);
                jButton5.setEnabled(true);
                jButton6.setEnabled(true);
                Ncancion inicio = new Ncancion();
                inicio=(Ncancion)vmusica.elementAt(0);
                ncancion.setText(inicio.getNcancion());
                art.setText(inicio.getArtist());
                album.setText(inicio.getAlbu());
                genero.setText(inicio.getGener());
                                            }
                else{
                jButton4.setEnabled(false);
                jButton2.setEnabled(false);
                jButton3.setEnabled(false);
                jButton5.setEnabled(false);
                jButton6.setEnabled(false);
                ncancion.setText("");
                art.setText("");
                album.setText("");
                genero.setText("");
                }
                 itr = vmusica.listIterator();
              

        }catch(Exception ex)
        {
            ex.printStackTrace();
        }    

}//GEN-LAST:event_cargaraBD

    public void quicksort(int izq,int der){
        String centro=null;
        int i=izq;
        int j =der;
        Ncancion objeto = new Ncancion();
        objeto=(Ncancion)vmusica.elementAt((izq+der)/2);

            switch(columna){
            case 1:
            centro=objeto.getNcancion();
               break;
            case 2:
            centro=objeto.getArtist();
              break;
            case 3:
            centro=objeto.getAlbu();
              break;
            case 4:
            centro=objeto.getGener();
             break;
                              }
        do{
           Ncancion objeto1 = new Ncancion();
           objeto1=(Ncancion)vmusica.elementAt(i);          
           Ncancion objeto2 = new Ncancion();
           objeto2=(Ncancion)vmusica.elementAt(j);
           String derecha=null;
           String izquierda=null;
            switch(columna){
            case 1:
            derecha=objeto2.getNcancion();
            izquierda=objeto1.getNcancion();
               break;
            case 2:
            derecha=objeto2.getArtist();
            izquierda=objeto1.getArtist();
              break;
            case 3:
            derecha=objeto2.getAlbu();
            izquierda=objeto1.getAlbu();
              break;
            case 4:
            derecha=objeto2.getGener();
            izquierda=objeto1.getGener();
             break;
                              }
           while(izquierda.compareTo(centro)<0){
            i++;
            objeto1 = new Ncancion();
            objeto1=(Ncancion)vmusica.elementAt(i);
           switch(columna){
            case 1:
            izquierda=objeto1.getNcancion();
               break;
            case 2:
            izquierda=objeto1.getArtist();
              break;
            case 3:
            izquierda=objeto1.getAlbu();
              break;
            case 4:
            izquierda=objeto1.getGener();
             break;
                              }
           }
            while(derecha.compareTo(centro)>0){
             j--;
             objeto2 = new Ncancion();
             objeto2=(Ncancion)vmusica.elementAt(j);
                 switch(columna){
            case 1:
            derecha=objeto2.getNcancion();
               break;
            case 2:
            derecha=objeto2.getArtist();
              break;
            case 3:
            derecha=objeto2.getAlbu();
              break;
            case 4:
            derecha=objeto2.getGener();
             break;
                              }
                                              }
                if (i <= j){
                 Ncancion aux = new Ncancion();
                 aux=(Ncancion)vmusica.elementAt(i);
                 vmusica.setElementAt(objeto2,i);
                 vmusica.setElementAt(aux,j);
                 i++;
                 j--;
                            }
            }while (i <= j);
                if(izq < j){
                quicksort(izq,j);
                conta++;
                           }
                 if(i < der){
                 quicksort(i,der);
                 conta++;
                            }
                 
    }
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new cdatos().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem Basedatos;
    private javax.swing.JTextField album;
    private javax.swing.JTextField art;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JTextField genero;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JFrame jFrame1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuBar jMenuBar2;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JMenuItem jMenuItem6;
    private javax.swing.JMenuItem jMenuItem8;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JRadioButton jRadioButton3;
    private javax.swing.JRadioButton jRadioButton4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField ncancion;
    // End of variables declaration//GEN-END:variables

   
    }

